package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.http.HttpUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.errorprone.annotations.Var;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.ReservationDto;
import com.zzyl.entity.Reservation;
import com.zzyl.enums.BasicEnum;
import com.zzyl.enums.ReservationStatus;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ReservationMapper;
import com.zzyl.service.ReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.CountTimesVo;
import com.zzyl.vo.ReservationVo;
import jdk.jshell.Snippet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ReservationServiceImpl implements ReservationService {
    @Autowired
    private ReservationMapper reservationMapper;
    @Override   //根据手机号查询reservation表格中的 该手机号的预约状态 统计是否取消次数>3 抛出异常
    public  Integer selectReservate() {
        Long userId = UserThreadLocal.getUserId();
        Integer count= reservationMapper.selectReservate(userId);
        if (count>3){
            throw new BaseException(BasicEnum.RESERVATION_COUNT_UPPER_LIMIT);
        }
        return count;
    }

    @Override
    public List<CountTimesVo> checkRemainderNumber(Long time) {
        //根据开始时间 和结束时间查询 统计该时间段内状态为预约的人数
        LocalDateTime localDateTime = LocalDateTimeUtil.of(time);
        LocalDateTime begin=localDateTime;
        LocalDateTime end=begin.plusHours(24);
        return reservationMapper.checkRemainderNumber(begin,end);
    }

    @Override
    public void save(ReservationDto reservationDto) {
        //获取登录用户id
        Long userId = UserThreadLocal.getUserId();

        Reservation reservation = BeanUtil.toBean(reservationDto, Reservation.class);
        if (reservationMapper.selectReservate(userId)>3){
            throw new BaseException(BasicEnum.RESERVATION_COUNT_UPPER_LIMIT);
        }
        reservation.setStatus(0); //设置状态
        reservation.setCreateBy(userId);//设置创建人
        reservationMapper.save(reservation);
    }

    @Override
    public PageResponse<ReservationVo> selectByPage(Integer pageNum, Integer pageSize, Integer status) {
        PageHelper.startPage(pageNum,pageSize);
        Page<Reservation>page= reservationMapper.selectList(UserThreadLocal.getUserId(),status);
        return PageResponse.of(page,ReservationVo.class);
    }

    @Override
    public void cancel(Long id) {
        Reservation reservation = new Reservation();
        reservation.setStatus(ReservationStatus.CANCELED.getOrdinal());
        reservation.setId(id);
       reservationMapper.update(reservation);
    }
}
